package br.com.jogo.neg;

import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import br.com.jogo.assets.Assets;
import br.com.jogo.neg.actions.MoveAction;
import br.com.jogo.neg.actions.UnitAction;

import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.Animation;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;

/**
 * Basic class of units in battle.
 * 
 * @author diasleon
 */
public class Unit extends GameObject {

	/**
	 * Stack of actions to be performed by the unit.
	 */
	private final Stack<UnitAction> actions = new Stack<UnitAction>();

	/**
	 * When equals 0, enable add new actions to the unit.
	 */
	public float coolDown = 0;

	/**
	 * Map of animations.
	 */
	public Map<String, Animation> animations = new HashMap<String, Animation>();

	/**
	 * The current frame.
	 */
	private TextureRegion currentFrame;

	/**
	 * Used in animations
	 */
	public float stateTime;

	public Team team;

	/**
	 * @param x
	 *            x coordinate of left x
	 * @param y
	 *            y coordinate of bottom y
	 */
	public Unit(float x, float y) {
		super(x, y, 32, 32);

		animations.put("", new Animation(0.2f, Assets.redmage[2][0]));

		animations.put(MoveAction.KEY, new Animation(0.2f,
				Assets.redmage[2][0], Assets.redmage[2][1],
				Assets.redmage[2][2]));

		animations.get(MoveAction.KEY).setPlayMode(Animation.LOOP_PINGPONG);
	}

	public void update(float delta) {

		this.stateTime += delta;

		if (!actions.empty()) {
			if (!actions.peek().isFinished()) {
				actions.peek().perform(this, delta);
			} else {
				actions.pop();
			}
		}

		if (coolDown > 0) {
			coolDown -= delta;
		} else {
			coolDown = 0;
		}

		currentFrame = animations.get("").getKeyFrame(stateTime);

		if (!actions.empty()) {
			currentFrame = animations.get(actions.peek().getKey()).getKeyFrame(
					stateTime);

		}

	}

	@Override
	public void Draw(SpriteBatch spriteBatch, float deltaTime) {

		if (team != null && team.side == Team.RIGHT) {
			currentFrame.flip(true, false);
		}
		
		if(this.coolDown > 0) {
			spriteBatch.setColor(Color.GRAY);
		}

		if (currentFrame != null) {
			spriteBatch.draw(currentFrame, this.bounds.x, this.bounds.y);
		}
		
		if(this.coolDown > 0) {
			spriteBatch.setColor(Color.WHITE);
		}

		if (team != null && team.side == Team.RIGHT) {
			currentFrame.flip(true, false);
		}
	}

	public boolean idle() {
		return actions.empty();
	}

	public void addAction(UnitAction action) {

		if (coolDown == 0) {
			coolDown = 2f;
			actions.push(action);
		}
	}
}
